// pages/mine/mine.js
/**我的页 */
const app = getApp()
const loginSession = require('../../utils/loginSession')

Page({
  /**页面的初始数据*/
  data: {
    userInfo: {},
    hasUserInfo: app.globalData.hasUserInfo,
    userRole: app.globalData.userRole || "普通用户",
    userMobile: app.globalData.phoneNumber,
    dialogShow: false,
    balance: '',
    meritsVirtues: app.globalData.meritsVirtues,
    session_key: app.globalData.session_key,
    fullName: '',
    isLogining: false
  },
  /**生命周期函数--监听页面加载*/
  onLoad: function (options) {
    this.data.userRole = app.userRole
    //必须在获取手机号之前登陆，否则第一次解密失败，而后才能成功。原因：需登录后session才生效，每次生成新code后旧code失效
    console.log('全局变量的值为app:', app.globalData)
  },
  /**生命周期期函数--页面显示时被触发 */
  onShow: function(e){
    //每次显示页面都检查session_key是否有效,无效则获取
    this.checkSessionKey()
    if(this.data.hasUserInfo){
      const mobile = app.globalData.mobile || wx.getStorageSync('user_phoneNumber')
      this.getUserSystemInfo(mobile)
    }
  },
  /**检查登录状态，状态无效从新登录 */
  checkSessionKey: async function() {
    let sessionKey = this.data.session_key || app.globalData.session_key
    console.log('本地存储sessionKey情况：',sessionKey)
    const isValid = await loginSession.isValidSessionKey()
    //sessionkey为空或失效生成新session返回
    if((sessionKey != undefined && sessionKey != '' && !isValid) || (sessionKey == '' || sessionKey == undefined)){
      const code = await loginSession.getCodeBylogin()
      sessionKey = await loginSession.getSessionkeyByCode(code)
      wx.setStorage({data: sessionKey, key: 'user_session_key'})
      this.setData({session_key: sessionKey})
      app.globalData.session_key = sessionKey
      return sessionKey
    }
    console.log('sessionKey不为空，检查session是否有效：', isValid)
    return sessionKey;
  },
 
  getPhoneNumber: async function(e) {
    this.setData({ isLogining: true })
    setTimeout(() => { this.setData({ isLogining: false }) }, 60000)
    const encrypData = e.detail.encryptedData
    const iv = e.detail.iv
    const sessionKey = await this.checkSessionKey()
    if(sessionKey=='' || sessionKey == undefined){
      console.error('code不能为空.')
      this.setData({ isLogining: false })
      return;
    }
    console.info('sessionKey值为：',sessionKey)
    const mobile = await this.decryptDataCallCloud(encrypData,iv,sessionKey)
    if(!mobile){
      this.setData({ isLogining: false })
      console.error('手机号解密失败.')
      return;
    }
    const info = await this.getUserSystemInfo(mobile)
    if(info == undefined){
      console.error('手机号解密失败.')
      this.setData({ isLogining: false })
      wx.showToast({title: "登录失败", icon: "error", duration: 2000})
      return;
    }
    this.setData({hasUserInfo: true, userMobile: mobile, isLogining: false})
    app.globalData.phoneNumber = mobile //全局设置，首次登录后点击功德主设置时显示
    wx.setStorage({ data: mobile, key: 'user_phoneNumber',})
  },
  /**调用云函数 */
  decryptDataCallCloud: async function(encrypData,iv,sessionKey){
    return await new Promise((resolve,reject)=>{
      wx.cloud.callFunction({
        name: "encryOrDecryp",
        data: { encryptedData: encrypData, iv: iv, session_key: sessionKey, reqType: 'decryptMobile' },
        success: function(res){
          console.log('云函数解密返回结果为：',res)
          const result = res.result
          if(result != null){
            const mobile =  result.data.phoneNumber
            resolve(mobile)
          }
          resolve(undefined)
          console.log("globalData:",app.globalData)
        },
        fail: res => {
          wx.showToast({title:"登录失败",icon: "error",duration: 2000})
          resolve(undefined)
        }
      })
    })
  },
  //获取用户系统信息
  getUserSystemInfo: async function(mobile){
    const that = this
    return await new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: "findCollectionById",
        data: { mobile: mobile, collectionName: "kindPersonInfo", reqType: 'findInfoByMobile' },
        success: function(res){
          console.log('用户系统信息为：',res)
          const data = res.result.data
          if(data == undefined || data == null){ 
            console.error("用户信息为空或不存在.")
            wx.showToast({title: "操作失败", icon: "error", duration: 2000})
            resolve(undefined)
            return ;
          }
          const info = data[0]
          const userRole = info.roles //角色
          const kindPeopleId = info._id
          const fullName = info.fullName
          const userMerits = info.meritsVirtues //功德主名，手机号首次登录时可能为空
          if(userMerits != "" && userMerits != undefined && userMerits != null){
            app.globalData.meritsVirtues = userMerits
            wx.setStorage({ data: userMerits, key: 'user_meritsVirtues'})
            that.setData({meritsVirtues: userMerits})
          }
          if(fullName != '' && fullName != undefined && fullName != null){
            app.globalData.fullName = fullName
            wx.setStorage({ data: fullName, key: 'user_fullName'})
            that.setData({fullName: fullName})
          }
          const balance = info.balance //余额
          that.setData({balance: balance,userRole: userRole})
          app.globalData.hasUserInfo = true
          app.globalData.userRole = userRole
          app.globalData.kindPeopleId = kindPeopleId
          wx.setStorage({ data: userRole, key: 'user_role',})
          wx.setStorage({ data: kindPeopleId, key: 'user_kindPeopleId'})
          resolve(info)
        },
        fail: res => {
          wx.showToast({title:"获取信息失败",icon: "error",duration: 2000})
          resolve(undefined)
        }
      })
    })
  },
  //基础设置
  baseSetting: function(e){
    if(!this.data.hasUserInfo){
      wx.showToast({title:"请先登录",icon: "icon-box-img",duration: 2000})
      return;
    }
    wx.navigateTo({ url: './baseSet/baseSet'})
  },
  //管理员设置
  roleSetting: function(e) {
    if(!this.data.hasUserInfo){
      wx.showToast({title: "请先登录", icon: "icon-box-img", duration: 2000})
      return;
    }
    wx.navigateTo({ url: './roleSet/roleSet'})
  },
  //退出按钮
  userExit: function(e){
    if(app.globalData.hasUserInfo){
      this.setData({
        hasUserInfo: false,
        userMobile: '',
        userRole: "普通用户",
        balance: '0.00'
      })
      app.globalData = {}
      wx.clearStorage()
    }
  },
  //支付按钮
  chargeBtnClickHandle: function(e){
    if(!this.data.hasUserInfo){
      wx.showToast({title:"请先登录",icon: "error",duration: 2000})
      return;
    }
    const meritsVirtues = this.data.meritsVirtues
    if(meritsVirtues == '' || meritsVirtues == undefined){
      wx.showToast({title:"请绑定功德主名",icon: "error",duration: 2000})
      return;
    }
    wx.navigateTo({url: './payOrder/payOrder'})
  },
  //功德主类表维护
  meritMasterListMaintainSetting: function(e){
    console.log('功德主类表维护...',e)
    if(!this.data.hasUserInfo){
      console.error('请先登录.');
      wx.showToast({title: "请先登录",icon: "error",duration: 2000})
      return;
    }
    wx.navigateTo({ url: './meritMasterMaintain/meritMasterMaintain'})
  },
  //名称金额类表
  nameAmountClickHandle: function(e){
    console.log('e: ',e)
    wx.navigateTo({ url: './nameAmountTable/nameAmountTable'})
  }
})